﻿using UnityEngine;

namespace JH
{  /// <summary>
    /// 获取屏幕边界
    /// </summary>
    public static class GetScreenBoundExtension
    {
        /// <summary>
        /// 计算一个RectTransform的屏幕边界
        /// </summary>
        public static (float xMin, float xMax, float yMin, float yMax) GetScreenBoundsEm(
            this RectTransform rectTransform, Camera camera = null)
        {
            //获取相机
            var canvas = rectTransform.GetComponentInParent<Canvas>();
            camera = canvas.renderMode == RenderMode.ScreenSpaceOverlay ? null : camera != null ? camera : Camera.main;
            Vector3[] corners = new Vector3[4];

            //获取世界坐标
            rectTransform.GetWorldCorners(corners);

            //转换为屏幕坐标
            for (int i = 0; i < 4; i++) corners[i] = RectTransformUtility.WorldToScreenPoint(camera, corners[i]);

            //计算边界 xMin xMax 
            float xMin = Mathf.Min(corners[0].x, corners[1].x, corners[2].x, corners[3].x);
            float xMax = Mathf.Max(corners[0].x, corners[1].x, corners[2].x, corners[3].x);

            //计算边界 yMin yMax
            float yMin = Mathf.Min(corners[0].y, corners[1].y, corners[2].y, corners[3].y);
            float yMax = Mathf.Max(corners[0].y, corners[1].y, corners[2].y, corners[3].y);

            //返回边界
            return (xMin, xMax, yMin, yMax);
        }
        
        /// <summary>
        ///  获取一个RectTransform的屏幕边界
        /// </summary>
        public static Rect GetScreenBoundsRectEm(this RectTransform rectTransform, Camera camera = null)
        {
          var bounds=  GetScreenBoundsEm(rectTransform, camera);

            return new Rect( bounds.xMin, bounds.yMin, bounds.xMax - bounds.xMin, bounds.yMax - bounds.yMin);
        }
    }
}